package com.world.rickcloudendpoint.common.utils;

/**
 * @description: 小端序
 * @author: jlsong
 * @date: 2021/12/21 22:28:32
 * @version: 1.0
 */
public class LittleEndian implements Endian {
    @Override
    public long getLong(byte[] bytes) {
        return (0xffL & (long) bytes[7])
                | (0xff00L & (long) bytes[6] << 8)
                | (0xff0000L & (long) bytes[5] << 16)
                | (0xff000000L & (long) bytes[4] << 24)
                | (0xff00000000L & (long) bytes[3] << 32)
                | (0xff0000000000L & (long) bytes[2] << 40)
                | (0xff000000000000L & (long) bytes[1] << 48)
                | (0xff00000000000000L & (long) bytes[0] << 56);
    }

    @Override
    public int getInt(byte[] bytes) {
        return (bytes[0] & 0xff) << 24
                | (bytes[1] & 0xff) << 16
                | (bytes[2] & 0xff) << 8
                | (bytes[3] & 0xff);
    }

    @Override
    public short getShort(byte[] bytes) {
        return (short) ((bytes[0] & 0xff) << 8
                | (bytes[1] & 0xff));
    }

    @Override
    public char getChar(byte[] bytes) {
        return (char) ((bytes[0] & 0xff) << 8
                | (bytes[1] & 0xff));
    }

    @Override
    public byte[] getLongBytes(long val) {
        return new byte[]{
                (byte) ((val >> 56) & 0xFF),
                (byte) ((val >> 48) & 0xFF),
                (byte) ((val >> 40) & 0xFF),
                (byte) ((val >> 32) & 0xFF),
                (byte) ((val >> 24) & 0xFF),
                (byte) ((val >> 16) & 0xFF),
                (byte) ((val >> 8) & 0xFF),
                (byte) (val & 0xFF)
        };
    }

    @Override
    public byte[] getIntBytes(int val) {
        return new byte[]{
                (byte) ((val >> 24) & 0xFF),
                (byte) ((val >> 16) & 0xFF),
                (byte) ((val >> 8) & 0xFF),
                (byte) (val & 0xFF)
        };
    }

    @Override
    public byte[] getShortBytes(short val) {
        return new byte[]{
                (byte) ((val >> 8) & 0xFF),
                (byte) (val & 0xFF)
        };
    }

    @Override
    public byte[] getCharBytes(char val) {
        return new byte[0];
    }
}
